package com.cnhis.onehis;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.cnhis.cloudhealth.commons.util.PinYinUtilForLucence;

public class LuceneCreateIndex
{
   private IndexWriter indexWriter = null;

   public LuceneCreateIndex( String indexDir ) throws Exception
   {
      // IKAnalyzer 有独特之处，同时支持多种语言的分词
      Analyzer analyzer = new IKAnalyzer();
      Directory directory = FSDirectory.open( Paths.get( indexDir ) );
      IndexWriterConfig indexWriterConfig = new IndexWriterConfig( analyzer );
      indexWriter = new IndexWriter( directory, indexWriterConfig );
   }

   private void createIndex(List<Map<String, Object>> list)
       throws Exception
   {
       for(Map<String, Object> teMap : list)
       {
           Document document = getDocument(teMap);
           indexWriter.addDocument(document);
           System.out.println("已建立索引文件:" + teMap.get("name"));
       }
       indexWriter.close();
   }
   
   private Document getDocument(Map<String, Object> map)
       throws Exception
   {
       Document document = new Document();
       for(String key : map.keySet())
       {
           document.add(new TextField(key, map.get(key).toString(),Field.Store.YES));
       }
       return document;
   }

   public static void main( String[] args )
   {
      String indexDir = "D:\\luceneTest";// 索引文件生成目录
      try
      {
          List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
          Map<String, Object> temp1 = new HashMap<String, Object>();
          temp1.put("name", "50%葡萄糖注射液（高糖）");
          temp1.put("type", "1");
          temp1.put("shouzimu", PinYinUtilForLucence.getFirstSpell("50%葡萄糖注射液（高糖）"));
          list.add(temp1);
          Map<String, Object> temp2 = new HashMap<String, Object>();
          temp2.put("name", "0.9%氯化钠注射液");
          temp2.put("type", "1");
          temp2.put("shouzimu", PinYinUtilForLucence.getFirstSpell("0.9%氯化钠注射液"));
          list.add(temp2);
         new LuceneCreateIndex( indexDir ).createIndex( list );
      }
      catch ( Exception e )
      {
         e.printStackTrace();
      }
   }
}